package com.github.codemperor.gateway.fitler;

import com.github.codemperor.api.base.BaseCodeEnum;
import com.github.codemperor.core.token.BaseToken;
import com.github.codemperor.core.token.CurrentUserInfo;
import com.github.codemperor.core.token.HeaderConst;
import com.github.codemperor.core.token.JwtToken;
import com.github.codemperor.gateway.config.BaseFilter;
import com.github.codemperor.gateway.config.ZuulConstants;
import com.github.codemperor.gateway.context.FilterContext;
import com.netflix.zuul.context.RequestContext;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * @author codemperor
 * @description 前端个人中心等部分接口token校验
 */
@Component
@Slf4j
public class WebsiteTokenFilter extends BaseFilter {

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return ZuulConstants.WEBSITE_TOKEN_FILTER_ORDER;
    }

    @Override
    public boolean shouldFilter() {
        return FilterContext.websiteTokenFilterEnabled.get();
    }

    @Override
    public Object run() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        try {
            String authToken = request.getHeader(HeaderConst.HEADER_FRONTEND_TOKEN);
            BaseToken token = JwtToken.build().frontend().parseToken(authToken);

            CurrentUserInfo user = FilterContext.currentUserInfo.get();
            user.setUserId(token.getUserId());
            user.setUserName(token.getUserName());
            user.setUserRole(token.getRole());

            log.debug("[WebsiteTokenFilter] user: {}", user);

        } catch (Exception e) {
            if (e instanceof ExpiredJwtException) {
                log.error("[WebsiteTokenFilter] token ExpiredJwtException", e);
            } else if (e instanceof IllegalArgumentException) {
                //token不存在
                log.error("[WebsiteTokenFilter] token IllegalArgumentException", e);
            } else {
                //其他错误
                log.error("[WebsiteTokenFilter] token other error", e);
            }

            FilterContext.endingException.set(BaseCodeEnum.LOGIN);
        }

        return null;
    }
}
